﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Bordspil.Models;
using System.Web.Security;

namespace Bordspil.Controllers
{
    public class GroupController : Controller
    {
        private IGroupRepository m_repository = null; 

        public GroupController()
        {
            m_repository = new GroupRepository();
        }

      public GroupController(IGroupRepository rep)
       {
          m_repository = rep;
       }

        //
        // GET: /Group/

        public ActionResult Index(string userName)
        {
           //skilar gruppum sem notandi er i og nyjasta er efst
            var result = from u in m_repository.GetAllGroupMembers()
                         orderby u.GroupId descending
                         where u.UserProfile.UserName == userName
                         select u;

            return View(result);
        }

        public JsonResult GetAllGroups()
        {
            //skilar ollum gruppum i json...eg elska json
            var result = from g in m_repository.GetAllGroups()
                         orderby g.GroupId ascending
                         select g;

            return Json(result, JsonRequestBehavior.AllowGet);
        }


        public ActionResult CreateGroup()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateGroup(Group groupp)
        {
            if (ModelState.IsValid)
            {
                if (groupp.GroupName == null)
                {
                    //ef ekkert nafn er skrifad ta refreshad sidan bara...getur ekki buid til gruppu med neitt nafn
                    return View();
                }

                AppDataContext g = new AppDataContext();

                //athuga hvort gruppa med tessu nafni er til
                var isTil = (from i in g.Groups
                             where i.GroupName == groupp.GroupName
                             select i).SingleOrDefault();

                if (isTil != null)
                {
                    return View(); //ef gruppan er til ta er sidan refreshud, tyrfti ad skila einhverjum villuskilabodum.
                }

                //skilgreini eiganda
                var owner = (from o in g.UserProfile
                             where o.UserName == User.Identity.Name
                             select o).SingleOrDefault();

                groupp.UserOwnerId = owner.UserId;
                m_repository.AddGroup(groupp);
                m_repository.Save();

                //adda owner i nyju gruppuna sina
                GroupMembers addOwner = new GroupMembers();
                addOwner.UserId = owner.UserId;
                addOwner.GroupId = groupp.GroupId;
                m_repository.AddMember(addOwner);
                m_repository.Save();

                //hendi notanda aftur a /Group/Index med notendanafniu sem parameter
                return RedirectToAction("Index", new { userName = owner.UserName });
            }

            return View(groupp);
        }

        ////
        //// GET: /Group/Edit/5
        public ActionResult EditGroup(int id = 0)
        {
            AppDataContext db = new AppDataContext();
            //saekji eigandan
            var isItOwner = (from o in db.UserProfile
                             join s in db.Groups on o.UserId equals s.UserOwnerId
                             where id == s.GroupId
                             select o.UserName).SingleOrDefault();

            //passa ad eigandi gruppu se ad breyta
            if (isItOwner != User.Identity.Name)
            {
                return RedirectToAction("Index", "Home");
            }


            Group group = db.Groups.Find(id);

            if (group == null)
            {
                //ef gruppan finnst ekki ta er hent a indexid
                return RedirectToAction("Index", "Home");
            }
            return View(group);
        }

        //
        // POST: /Group/Edit/5
        [HttpPost]
        public ActionResult EditGroup(Group group)
        {
            AppDataContext db = new AppDataContext();
            if (ModelState.IsValid)
            {
                //saekji eiganda gruppunar
                var owner = (from o in db.UserProfile
                             where o.UserName == User.Identity.Name
                             select o).SingleOrDefault();

                if (group.GroupName == null)
                {
                    return View();
                }

                //ownerin er ennta ownerinn en basicly breytist bara nafnid.
                group.UserOwnerId = owner.UserId;

                db.Entry(group).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index", "Group", new { userName = User.Identity.Name } );
            }
            return View(group);
        }

        public JsonResult AddMemberToGroup(int userId, int groupId)
        {
            //ser um ad setja notanda i gruppi i rauntima !
            GroupMembers n = new GroupMembers();
            n.GroupId = groupId;
            n.UserId = userId;
            m_repository.AddMember(n);
            m_repository.Save();

            return Json("ok", JsonRequestBehavior.AllowGet);
        }

        public ActionResult GroupProfile(string groupName)
        {
            //skilar profile sidu akvedin profiles
            var users = from m in m_repository.GetAllGroupMembers()
                        where m.Group.GroupName == groupName
                        select m;

            return View(users);
        }

        public JsonResult GetGroupMembers(int? groupId)
        {
            //skilar medlimum gruppu og skilar nidurstodum i json
            var result = from m in m_repository.GetAllGroupMembers()
                         where m.GroupId == groupId
                         select m;

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetGroupsByUser(string userName)
        {
            //skilar hopum sem gefin notandi er i 
            AppDataContext db = new AppDataContext();
            var result = (from o in db.Groups
                          join b in db.GroupMembers on o.GroupId equals b.GroupId
                          join c in db.UserProfile on b.UserId equals c.UserId
                          where c.UserName == userName
                          select o);

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        
        public JsonResult DeleteGroup(int id)
        {
            //fall ser um ad eyda gruppu
            if (ModelState.IsValid)
            {
                AppDataContext db = new AppDataContext();

                var isItOwner = (from o in db.UserProfile
                                 join s in db.Groups on o.UserId equals s.UserOwnerId
                                 where id == s.GroupId
                                 select o.UserName).SingleOrDefault();

                //passa ad eigandi gruppu se ad breyta
                if (isItOwner != User.Identity.Name)
                {
                    return Json("Ert ekki eigandi", JsonRequestBehavior.AllowGet);
                }

                //finn gruppu og eydi ur database
                Group group = db.Groups.Find(id);
                db.Groups.Remove(group);
                db.SaveChanges();
                return Json("Farin", JsonRequestBehavior.AllowGet);
            }

            return Json("villa", JsonRequestBehavior.AllowGet);
        }


        public JsonResult LeveGroup(int? groupId, string userName)
        {
            if (ModelState.IsValid)
            {
                AppDataContext db = new AppDataContext();

                var findUserId = (from u in db.UserProfile
                                  where u.UserName == userName
                                  select u).SingleOrDefault();

                if (findUserId == null)
                {
                    //athuga hvort notandi finnst ekki oruglega i toflu
                    return Json("Notandi finnst ekki", JsonRequestBehavior.AllowGet);
                }

                var findUserInGroup = (from g in m_repository.GetAllGroupMembers()
                                       where g.GroupId == groupId && findUserId.UserId == g.UserId
                                       select g.Id).SingleOrDefault();

                if (findUserId.UserName != User.Identity.Name)
                {
                    //hvort rettur notandi se ekki oruglega ad reyna ad segja sig ur gruppunni, svo jon geti ekki bara hent sigurdi ur gruppunni
                    return Json("Ert ekki réttur notandi", JsonRequestBehavior.AllowGet);
                }

                //ef vid komumst svona langt ta ma henda notanda ur groupmembers toflunni og ta er notandi ekki lengur medlimur i gruppunni
                GroupMembers groupMember = db.GroupMembers.Find(findUserInGroup);
                db.GroupMembers.Remove(groupMember);
                db.SaveChanges();


                return Json("Hættur", JsonRequestBehavior.AllowGet);

            }

            return Json("Villa", JsonRequestBehavior.AllowGet);
        }

       protected override void Dispose(bool disposing)
       {
           AppDataContext db = new AppDataContext();
           db.Dispose();
           base.Dispose(disposing);
       }

    }
}